# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/14'
__author__ = 'Just'
__filename__ = 'form'
"""
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Regexp, Email, length
from app.libs.enums import ClientTypeEnum
from app.libs.error_code import ParameterException
from app.model.banner import Banner
from app.model.user import User
from app.validators.base import FormBase


class ClientForm(FormBase):
    """通用客户端 注册 参数检验"""
    account = StringField(validators=[DataRequired(message='账号为空'), length(min=5, max=32)])
    password = StringField()
    type = IntegerField(validators=[DataRequired(message='客户端类型为空')])

    def validate_type(self, value):
        """验证客户端类型是否存在"""
        try:
            client = ClientTypeEnum(value.data)
        except ValueError as e:
            raise ParameterException(msg='客户端类型错误', error_code=6011)
        self.type.data = client


class ClientEmailForm(ClientForm):
    """邮箱账号 注册参数检验"""
    account = StringField(validators=[Email(message='请用邮箱账号'), length(min=10, max=32)])
    password = StringField(validators=[
        DataRequired(message='密码不能为空'),
        Regexp(r'^[A-Za-z][0-9]{5,21}', message='密码首位大小写字母且长度大于等于6,小于等于22')
    ])
    nickname = StringField()  # validators=[DataRequired(message='请用输入昵称')]

    def validate_account(self, value):
        """验证账号"""
        if User.query.filter_by(account=value.data).first():
            raise ParameterException(msg='账号已被注册', error_code=6000)


class ClientMinaForm(ClientForm):
    pass


class TokenForm(FormBase):
    token = StringField(validators=[DataRequired(message='没有令牌')])


class ComicListForm(FormBase):
    """漫画列表"""
    start = IntegerField()
    limit = IntegerField()

    def validate_start(self, value):
        """start 需为 int"""
        if value.data is None:
            self.start.data = 0
        else:
            try:
                res = int(value.data)
            except Exception as e:
                raise ParameterException(msg='传入的起始start不是int,请检查', error_code=3001)
            self.start.data = res

    def validate_limit(self, value):
        """start 需为 int"""
        if value.data is None:
            self.limit.data = 10
        else:
            try:
                res = int(value.data)
            except Exception as e:
                raise ParameterException(msg='传入的起始limit不是int,请检查', error_code=3002)
            self.limit.data = res


class ComicSearchForm(ComicListForm):
    """搜索"""
    q = StringField(validators=[DataRequired('请输入关键字')])


class ComicReadForm(FormBase):
    """阅读参数检验"""
    cid = IntegerField(validators=[DataRequired(message='没传漫画id')])
    sid = IntegerField(validators=[DataRequired(message='没传漫画的章节id')])


class BannerChangeForm(FormBase):
    """添加Banner参数检验"""
    name = StringField(validators=[DataRequired(message='请传入banner名称')])
    description = StringField()


class BannerDataForm(FormBase):
    """给某Banner添加一条数据BannerItem 参数检验"""
    bid = IntegerField(validators=[DataRequired(message='请传入Banner bid')])
    title = StringField(validators=[DataRequired(message='请填入名称')])
    description = StringField()
    type = IntegerField()
    link = StringField(validators=[DataRequired(message='没有传入跳转的地址')])
    image = StringField(validators=[DataRequired(message='没有传入头图地址')])


class BannerDataDeleteForm(FormBase):
    """某Banner 移除一条记录BannerItem 参数检验"""
    bid = IntegerField(validators=[DataRequired(message='请传入Banner bid')])
    items = StringField(validators=[DataRequired(message='请传入需要移除的条目id号')])

    def validate_items(self, value):
        # 字符串,已逗号分割 '1,2,3,4,5'
        # 尝试转换int类型的list
        if not isinstance(value.data, str):
            raise ParameterException(msg='添加记录 items参数应为字符串', error_code=2001)
        temp = []
        if ',' in value.data:
            _list = value.data.split(',')
            try:
                _list = [int(str.strip(item)) for item in _list]
            except Exception:
                raise ParameterException(msg=' {} 包含 非 BannerItem id号,请检查'.format(_list), error_code=2002)
            temp = list(set(_list))
        else:
            try:
                _list = int(value.data)
            except Exception:
                raise ParameterException(msg=' {} 不是BannerItem id号,请检查'.format(value.data), error_code=2003)
            temp.append(_list)
        self.items.data = temp


class ThemeChangeForm(FormBase):
    """添加/更新 主题参数检验"""
    title = StringField(validators=[DataRequired(message='请传入主题名称')])
    description = StringField()


class ThemeDataForm(FormBase):
    """添加主题关联数据 参数检验"""
    id = IntegerField(validators=[DataRequired(message='请传入主题id')])
    comics = StringField(validators=[DataRequired(message='请传入漫画cid字符串')])

    def validate_comics(self, value):
        # 其实是一组漫画cid的字符串,已逗号分割 '1,2,3,4,5'
        # 尝试转换int类型的list
        if not isinstance(value.data, str):
            raise ParameterException(msg='添加记录 comic参数应为字符串', error_code=4002)
        temp = []
        if ',' in value.data:
            _list = value.data.split(',')
            try:
                _list = [int(str.strip(item)) for item in _list]
            except Exception:
                raise ParameterException(msg=' {} 包含 非 漫画id号,请检查'.format(_list), error_code=4003)
            temp = list(set(_list))
        else:
            try:
                _list = int(value.data)
            except Exception:
                raise ParameterException(msg=' {} 不是漫画id号,请检查'.format(_list), error_code=4003)
            temp.append(_list)
        self.comics.data = temp


class DeleteMyComicForm(FormBase):
    """删除我的漫画 参数检验"""
    comics = StringField(validators=[DataRequired(message='请传入准备删除的漫画cid字符串')])

    def validate_comics(self, value):
        # 其实是一组漫画cid的字符串,已逗号分割 '1,2,3,4,5'
        # 尝试转换int类型的list
        if not isinstance(value.data, str):
            raise ParameterException(msg='comic参数应为字符串', error_code=5002)
        temp = []
        if ',' in value.data:
            _list = value.data.split(',')
            try:
                _list = [int(str.strip(item)) for item in _list]
            except Exception:
                raise ParameterException(msg=' {} 包含 非 漫画id号,请检查'.format(_list), error_code=5003)
            temp = list(set(_list))
        else:
            try:
                _list = int(value.data)
            except Exception:
                raise ParameterException(msg=' {} 不是漫画id号,请检查'.format(_list), error_code=5003)
            temp.append(_list)
        self.comics.data = temp
